package com.xxl.job.admin.controller;

import com.xxl.job.admin.controller.annotation.PermissionLimit;
import com.xxl.job.admin.core.model.XxlJobGroup;
import com.xxl.job.admin.core.model.XxlJobInfo;
import com.xxl.job.admin.dao.XxlJobGroupDao;
import com.xxl.job.admin.service.XxlJobService;
import com.xxl.job.core.biz.model.ReturnT;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 扩展api
 * @author liaoyz
 * @date 2022/05/27 18:05 
 */
@RestController
@RequestMapping("/ext")
public class ExtApiController {
    @Resource
    public XxlJobGroupDao xxlJobGroupDao;
    @Resource
    private XxlJobService xxlJobService;

    @PostMapping("/jobgroup/get-group-id")
    @PermissionLimit(limit = false)
    public ReturnT<Integer> getGroupId(@RequestBody XxlJobGroup jobGroup) {
        Integer groupId = xxlJobGroupDao.findByAppname(jobGroup.getAppname());
        return new ReturnT<>(groupId);
    }

    @PostMapping("/jobinfo/add")
    @PermissionLimit(limit = false)
    public ReturnT<String> add(@RequestBody XxlJobInfo jobInfo) {
        return xxlJobService.add(jobInfo);
    }

    @PostMapping("/jobinfo/update")
    @PermissionLimit(limit = false)
    public ReturnT<String> update(@RequestBody XxlJobInfo jobInfo) {
        return xxlJobService.update(jobInfo);
    }

    @PostMapping("/jobinfo/remove")
    @PermissionLimit(limit = false)
    public ReturnT<String> remove(@RequestBody IdDTO data) {
        return xxlJobService.remove(data.getId());
    }

    @PostMapping("/jobinfo/stop")
    @PermissionLimit(limit = false)
    public ReturnT<String> pause(@RequestBody IdDTO data) {
        return xxlJobService.stop(data.getId());
    }

    @PostMapping("/jobinfo/start")
    @PermissionLimit(limit = false)
    public ReturnT<String> start(@RequestBody IdDTO data) {
        return xxlJobService.start(data.getId());
    }

    @PostMapping("/jobinfo/add-and-start")
    @PermissionLimit(limit = false)
    public ReturnT<String> addAndStart(@RequestBody XxlJobInfo jobInfo) {
        ReturnT<String> returnT = xxlJobService.add(jobInfo);
        if (returnT.getCode() == ReturnT.SUCCESS_CODE) {
            xxlJobService.start(Integer.parseInt(returnT.getContent()));
        }
        return returnT;
    }

    public static class IdDTO {
        private Integer id;

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }
    }
}
